import { computed, onMounted, onUnmounted, ref } from "vue";
import { useStore } from "vuex";
import { GlobalDataProps } from "@/store";
import { Modal } from "ant-design-vue";
import {
  useRoute,
  RouterView,
  RouterLink,
  onBeforeRouteLeave,
} from "vue-router";

// editor 保存作品相关逻辑
function useSaveWork(disableSideEffects = false) {
  //1. 数据准备
  const store = useStore<GlobalDataProps>();
  const route = useRoute();
  const currentWorkId = route.params.id;
  const saveIsLoading = computed(() => store.getters.isOpLoading("saveWork"));
  const components = computed(() => store.state.editor.components);
  const page = computed(() => store.state.editor.page);
  const isDirty = computed(() => store.state.editor.isDirty);

  //保存函数
  const saveWork = () => {
    const { title, props, coverImg } = page.value;
    const payload = {
      title,
      coverImg,
      content: {
        components: components.value,
        props,
      },
    };
    store.dispatch("saveWork", {
      data: payload,
      urlParams: { id: currentWorkId },
    });
  };

  if(!disableSideEffects) {
    //自动保存
    let timer = 0;
    onMounted(() => {
      timer = setInterval(() => {
        if (isDirty.value) {
          saveWork();
        }
      }, 5000);
    });

    onUnmounted(() => {
      clearInterval(timer);
    });

    // 离开页面也要保存
    onBeforeRouteLeave((to, from, next) => {
      if (isDirty.value) {
        Modal.confirm({
          title: "作品未保存,是否保存?",
          okText: "保存",
          cancelText: "不保存",
          okType: "primary",
          onOk: async () => {
            await saveWork();
            next();
          },
          onCancel: () => {
            next();
          },
        });
      } else {
        next();
      }
    });
  }

  return {
    saveIsLoading,
    saveWork,
  };
}


export default useSaveWork;